import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/Layout.vue'

import SSOLogin from '@/views/sso-login/index.vue'
import Callback from '@/views/callback/index.vue'
import Login from '@/views/login/index.vue'
import { generateRoutes } from '@/router/permissions'
import NProgress from '@/router/nprogress'
import { useUserStore } from '@/store/user'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { showInMenu: false }
  },
  {
    path: '/sso-login',
    name: 'SSOLogin',
    component: SSOLogin,
    meta: { showInMenu: false }
  },
  {
    path: '/callback',
    name: 'Callback',
    component: Callback,
    meta: { showInMenu: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        meta: { title: '首页', showInMenu: true, icon: 'HomeFilled' },
        component: () => import('@/views/dashboard/index.vue')
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})



const whiteList = ['/login', '/sso-login', '/callback']; // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  if (whiteList.includes(to.path.toLowerCase())) {
    // 如果在白名单中，直接放行
    return next();
  }

  // 检查路由是否存在
  const matchedRoutes = router.resolve(to).matched;
  if (matchedRoutes.length === 0) {
    // 如果路由不存在，重定向到主页
    return next('/');
  }

  // 路由添加进去了没有及时更新 需要重新进去一次拦截
  if (!useUserStore().isAuthenticate) {
    return next(import.meta.env.VITE_USE_SSO === 'true' ? '/sso-login' : '/login');
  }

  // 获取权限列表进行接口访问 因为这里页面要切换权限
  const accessRoutes = await generateRoutes(router.options.routes);
  // hasRoles = false
  accessRoutes.forEach((item) => router.addRoute(item)); // 动态添加访问路由表

  next(); // 如果不传参数就会重新执行路由拦截，重新进到这里
});

router.afterEach(() => {
  NProgress.done();
});

export default router